package com.event.management.backend.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.event.management.backend.dto.QuestionnaireAnswerDTO;
import com.event.management.backend.dto.QuestionnaireQueryParam;
import com.event.management.backend.dto.QuestionnaireTemplateDTO;
import com.event.management.backend.service.EventService;
import com.event.management.backend.service.QuestionnaireService;
import com.event.management.backend.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 问卷控制器
 */
@Api(tags = "问卷管理接口")
@RestController
@RequestMapping("/api")
public class QuestionnaireController {
    
    @Autowired
    private QuestionnaireService questionnaireService;
    
    @Autowired
    private EventService eventService;
    
    /**
     * 获取问卷模板列表
     * @param queryParam 查询参数
     * @return 问卷模板列表
     */
    @ApiOperation(value = "获取问卷模板列表", notes = "查询问卷模板列表（分页）")
    @GetMapping("/questionnaires/templates")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<Map<String, Object>> getTemplateList(QuestionnaireQueryParam queryParam) {
        IPage<QuestionnaireTemplateDTO> page = questionnaireService.getQuestionnairePage(queryParam);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("total", page.getTotal());
        result.put("pages", page.getPages());
        result.put("list", page.getRecords());
        
        return Result.success(result);
    }
    
    /**
     * 获取问卷模板详情
     * @param id 模板ID
     * @return 模板详情
     */
    @ApiOperation(value = "获取问卷模板详情", notes = "根据ID获取问卷模板详细信息")
    @GetMapping("/questionnaires/templates/{id}")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<QuestionnaireTemplateDTO> getTemplateDetail(
            @ApiParam(value = "模板ID", required = true) @PathVariable Long id) {
        if (id == null || id <= 0) {
            return Result.validateFailed("模板ID不合法");
        }
        
        QuestionnaireTemplateDTO templateDTO = questionnaireService.getQuestionnaireById(id);
        if (templateDTO == null) {
            return Result.error(404, "问卷模板不存在或已被删除");
        }
        
        return Result.success(templateDTO);
    }
    
    /**
     * 新建问卷模板
     * @param templateDTO 模板信息
     * @return 新建结果
     */
    @ApiOperation(value = "新建问卷模板", notes = "新建问卷模板（需要管理员或组织者权限）")
    @PostMapping("/questionnaires/templates")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<QuestionnaireTemplateDTO> addTemplate(
            @Validated @RequestBody QuestionnaireTemplateDTO templateDTO) {
        try {
            Long templateId = questionnaireService.addQuestionnaire(templateDTO);
            
            QuestionnaireTemplateDTO newTemplate = questionnaireService.getQuestionnaireById(templateId);
            return Result.success(newTemplate, "创建问卷模板成功");
        } catch (Exception e) {
            return Result.error(500, "创建问卷模板失败：" + e.getMessage());
        }
    }
    
    /**
     * 编辑问卷模板
     * @param id 模板ID
     * @param templateDTO 模板信息
     * @return 编辑结果
     */
    @ApiOperation(value = "编辑问卷模板", notes = "编辑问卷模板信息与题目（需要模板创建者本人或管理员权限）")
    @PutMapping("/questionnaires/templates/{id}")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<Boolean> updateTemplate(
            @ApiParam(value = "模板ID", required = true) @PathVariable Long id,
            @Validated @RequestBody QuestionnaireTemplateDTO templateDTO) {
        if (id == null || id <= 0) {
            return Result.validateFailed("模板ID不合法");
        }
        
        try {
            // 检查是否有权限修改此模板
            if (!questionnaireService.checkTemplateManagePermission(id)) {
                return Result.error(403, "您没有权限编辑此问卷模板");
            }
            
            boolean success = questionnaireService.updateQuestionnaire(id, templateDTO);
            if (!success) {
                return Result.error(404, "问卷模板不存在或已被删除");
            }
            
            return Result.success(success, "更新问卷模板成功");
        } catch (Exception e) {
            return Result.error(500, "更新问卷模板失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除问卷模板
     * @param id 模板ID
     * @return 删除结果
     */
    @ApiOperation(value = "删除问卷模板", notes = "删除问卷模板（需要管理员权限）")
    @DeleteMapping("/questionnaires/templates/{id}")
    @SaCheckRole("admin")
    public Result<Boolean> deleteTemplate(
            @ApiParam(value = "模板ID", required = true) @PathVariable Long id) {
        if (id == null || id <= 0) {
            return Result.validateFailed("模板ID不合法");
        }
        
        try {
            boolean success = questionnaireService.deleteQuestionnaire(id);
            return Result.success(success, "删除问卷模板成功");
        } catch (Exception e) {
            return Result.error(500, "删除问卷模板失败：" + e.getMessage());
        }
    }
    
    /**
     * 活动关联问卷
     * @param eventId 活动ID
     * @param templateId 模板ID
     * @return 关联结果
     */
    @ApiOperation(value = "活动关联问卷", notes = "将问卷模板关联到活动（需要活动创建者本人或管理员权限）")
    @PostMapping("/events/{eventId}/questionnaire/{templateId}")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<Boolean> associateQuestionnaire(
            @ApiParam(value = "活动ID", required = true) @PathVariable Long eventId,
            @ApiParam(value = "模板ID", required = true) @PathVariable Long templateId) {
        if (eventId == null || eventId <= 0 || templateId == null || templateId <= 0) {
            return Result.validateFailed("活动ID或模板ID不合法");
        }
        
        try {
            // 检查是否有权限管理此活动
            if (!eventService.checkEventManagePermission(eventId)) {
                return Result.error(403, "您没有权限管理此活动");
            }
            
            boolean success = questionnaireService.associateToEvent(eventId, templateId);
            return Result.success(success, "关联问卷模板成功");
        } catch (Exception e) {
            return Result.error(500, "关联问卷模板失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取问卷反馈列表
     * @param eventId 活动ID
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return 反馈列表
     */
    @ApiOperation(value = "获取问卷反馈列表", notes = "查询用户提交的问卷反馈（需要活动创建者本人或管理员权限）")
    @GetMapping("/questionnaires/results")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<Map<String, Object>> getQuestionnaireResults(
            @ApiParam(value = "活动ID", required = true) @RequestParam Long eventId,
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页条数", defaultValue = "10") @RequestParam(defaultValue = "10") Integer pageSize) {
        if (eventId == null || eventId <= 0) {
            return Result.validateFailed("活动ID不合法");
        }
        
        try {
            // 检查是否有权限查看此活动的问卷反馈
            if (!eventService.checkEventManagePermission(eventId)) {
                return Result.error(403, "您没有权限查看此活动的问卷反馈");
            }
            
            IPage<QuestionnaireAnswerDTO> page = questionnaireService.getQuestionnaireResults(eventId, pageNum, pageSize);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("total", page.getTotal());
            result.put("pages", page.getPages());
            result.put("list", page.getRecords());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, "获取问卷反馈失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询用户问卷提交记录
     * @param userId 用户ID
     * @param eventId 活动ID
     * @param templateId 问卷模板ID
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return 问卷提交记录列表
     */
    @ApiOperation(value = "查询用户问卷提交记录", notes = "查询哪个用户回答了哪个活动的哪个问卷(需要管理员或组织者权限)")
    @GetMapping("/questionnaires/user-submissions")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<Map<String, Object>> getUserQuestionnaireSubmissions(
            @ApiParam(value = "用户ID") @RequestParam(required = false) Long userId,
            @ApiParam(value = "活动ID") @RequestParam(required = false) Long eventId,
            @ApiParam(value = "问卷模板ID") @RequestParam(required = false) Long templateId,
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页条数", defaultValue = "10") @RequestParam(defaultValue = "10") Integer pageSize) {
        
        try {
            // 如果指定了活动ID，检查是否有权限查看此活动的问卷信息
            if (eventId != null && eventId > 0 && !eventService.checkEventManagePermission(eventId)) {
                return Result.error(403, "您没有权限查看此活动的问卷信息");
            }
            
            IPage<QuestionnaireAnswerDTO> page = questionnaireService.getUserQuestionnaireSubmissions(
                    userId, eventId, templateId, pageNum, pageSize);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("total", page.getTotal());
            result.put("pages", page.getPages());
            result.put("list", page.getRecords());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, "查询问卷提交记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 提交问卷反馈
     * @param answerDTO 问卷答案
     * @return 提交结果
     */
    @ApiOperation(value = "提交问卷反馈", notes = "用户提交问卷反馈")
    @PostMapping("/questionnaires/answers")
    @SaCheckLogin
    public Result<Boolean> submitQuestionnaire(@Validated @RequestBody QuestionnaireAnswerDTO answerDTO) {
        try {
            boolean success = questionnaireService.submitQuestionnaire(answerDTO);
            return Result.success(success, "提交问卷反馈成功");
        } catch (Exception e) {
            return Result.error(500, "提交问卷反馈失败：" + e.getMessage());
        }
    }
} 